package com.digicom.api.config;

import com.digicom.common.core.utils.SecurityUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Spring Security配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init() {
        // 初始化SecurityUtils中的RedisTemplate
        SecurityUtils.setRedisTemplate(redisTemplate);
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 安全配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // CSRF禁用，因为不使用session
            .csrf().disable()
            // 基于token，所以不需要session
            .sessionManagement().disable()
            // 允许跨域
            .cors()
            .and()
            // 对请求授权
            .authorizeRequests()
            // 静态资源，可匿名访问
            .antMatchers("/css/**", "/js/**", "/images/**", "/favicon.ico").permitAll()
            // 开放API接口，允许匿名访问
            .antMatchers("/api/**").permitAll()
            // 除上面外的所有请求全部需要鉴权认证
            .anyRequest().authenticated();
    }
} 